package com.hanbang.chu_xing_gao_zhao.utils;

import android.content.Context;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.myview.MyDialog;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog.MODE;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

/**
 * 显示连接对话框，打印成功或错误信息
 *
 * @param <T>
 * @author yang
 */
public abstract class MyRequestCallBack<T> extends RequestCallBack<T> {
    private Context context = null;
    private String dialogContent = "";
    private MyDialog myDialog = null;

    public final void setRateX(int rate) {
        super.setRate(rate);
    }

    @Override
    public void onCancelled() {
        super.onCancelled();
    }

    /**
     * 构造函数 参数是准备创建对话框 如果content为null 那么就代表这条http请求不弹出对话框
     */
    public MyRequestCallBack(Context context, String content) {

        this.context = context;
        dialogContent = content;
    }

    /**
     * 开始连接时显示动画
     */
    @Override
    public void onStart() {
        super.onStart();
        // 判断是否加载对话框
        if (context != null & dialogContent != null) {
            myDialog = new MyDialog(context, R.style.base_dialog, MODE.LOADDING);
            myDialog.setContent(dialogContent);
            myDialog.show();
        }
    }

    /**
     * 连接成功后提示
     */
    @Override
    public void onSuccess(ResponseInfo<T> responseInfo) {
        MyLog.e("onSuccess", responseInfo.result.toString());

        if (myDialog != null) {
            myDialog.dismiss();
        }
    }

    /**
     * 连接失败提示
     */
    @Override
    public void onFailure(HttpException error, String msg) {
        MyLog.e("onFailure", msg + " code" + error.getExceptionCode());
        if (myDialog != null) {
            myDialog.dismiss();
        }


        if (msg.contains("timed out")) {
            MyToast.show(context, "连接超时", Toast.LENGTH_SHORT);
        } else if (!NetWorkHelper.isNetworkAvailable(context)) {
            MyToast.show(context, "请检查网络设置", Toast.LENGTH_SHORT);
        } else if (error.getExceptionCode() == 500) {
            MyToast.show(context, "服务器异常", Toast.LENGTH_SHORT);
        } else if (error.getExceptionCode() == 0) {
            MyToast.show(context, "服务器无响应", Toast.LENGTH_SHORT);
        } else if (error.getExceptionCode() == -1) {
            MyToast.show(context, "请求异常", Toast.LENGTH_SHORT);
        }


    }

    /**
     * 打印加载到的数据长度
     */
    @Override
    public void onLoading(long total, long current, boolean isUploading) {
        super.onLoading(total, current, isUploading);

        MyLog.e("onLoading", "总长：" + total + "   加载到：" + current+isUploading);
    }
}
